package zk.tool.ui;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zk.tool.Threads;
import zk.tool.ZKClient;
import zk.tool.model.TreeItemData;
import zk.tool.util.AlertUtil;
import zk.tool.util.StringUtil;
import zk.tool.util.TreeCommon;

import java.net.URL;
import java.util.ResourceBundle;

public class AddNodeController extends AbstractController {
    private static final Logger log = LoggerFactory.getLogger(AddNodeController.class);
    private Stage stage;
    private TreeItem<TreeItemData> parentItem;

    @FXML
    private TextField nameIpt;

    @FXML
    private TextArea dataIpt;

    @FXML
    private Button saveBtn;

    @FXML
    private Button cancelBtn;


    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public boolean validateForm() {
        String name = nameIpt.getText();
        name = name == null ? null : name.trim();
        if (StringUtil.isBlank(name)) {
            AlertUtil.info("提示", "节点名称不能为空");
            return false;
        }

        return true;
    }

    public TreeItemData getFormData() {
        String name = nameIpt.getText();
        String data = dataIpt.getText();
        name = name == null ? null : name.trim();
        data = data == null ? null : data.trim();
        TreeItemData itemData = new TreeItemData("", name);
        itemData.setData(data);
        return itemData;
    }

    public void resetForm() {
        nameIpt.clear();
        dataIpt.clear();
        cancelBtn.setDisable(false);
        saveBtn.setDisable(false);
        saveBtn.setText("保存");
    }

    @FXML
    public void save() {
        if (!this.validateForm()) {
            return;
        }
        cancelBtn.setDisable(true);
        saveBtn.setText("保存中...");
        saveBtn.setDisable(true);

        Threads.TREE_LOAD_THREAD_POOL.execute(() -> {
            TreeItemData formData = this.getFormData();
            AppController controller = UIManager.getInstance().getController(AppController.class);
            if (controller == null) {
                return;
            }
            ZKClient client = controller.getClient();
            TreeItemData itemData = parentItem.getValue();

            if (!itemData.getPath().endsWith("/")) {
                formData.setPath(itemData.getPath() + "/" + formData.getName());
            }

            // 检查节点是否已存在
            try {
                if (client.isExists(formData.getPath())) {
                    AlertUtil.info("提示", "已存在的节点：[" + formData.getPath() + "]");
                    return;
                }
            } catch (Exception e) {
                log.error("check node stat exception", e);
                AlertUtil.exception("检查节点是否存在失败", e);
                return;
            }

            // 创建节点
            try {
                client.createNode(formData.getPath(), formData.getData());
                TreeCommon.refreshChildren(client, parentItem);
            } catch (Exception e) {
                log.error("create node exception", e);
                AlertUtil.exception("创建节点失败", e);
                return;
            }
            Platform.runLater(this::cancel);
        });
    }

    @FXML
    public void cancel() {
        this.resetForm();
        this.close();
    }

    public void close() {
        stage.close();
    }

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    public void setParentItem(TreeItem<TreeItemData> parentItem) {
        this.parentItem = parentItem;
    }
}
